<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import ScreenTable from "@/components/ScreenTable/index.vue";
import { ITableData, IQueryParams, ITableListItem } from "./data";
import { IResponseData } from "@/@types/utils.request";
import { queryList, update, save, removeData } from "./service";
import { ElMessage } from "element-plus";
import { ResultCodeEnum } from "@/enums/utils.request.enum";
import { useUserStore } from "@/store/user";
// import { useUserStore } from "@/store/user";
/* ====================== 表格 - 获取数据 S ============== */
// 表格 - 列表 - 初始化数据
const tableData = reactive<ITableData>({
	loading: false,
	list: [],
	pagination: {
		total: 0,
		current: 1,
		pageSize: 20,
		sizeChange: () => {},
		onChange: () => {},
	},
});

// const userStore = useUserStore();
const searchKey = reactive<IQueryParams>({
	departmentName: "",
});

// 表格 - index
const tableIndexMethod = (index: number) => {
	return index + (tableData.pagination.current - 1) * tableData.pagination.pageSize + 1;
};

const getList = async (key: IQueryParams): Promise<void> => {
	tableData.loading = true;
	try {
		const response: IResponseData<any> = await queryList({
			pageSize: tableData.pagination.pageSize,
			pageNum: tableData.pagination.current,
			data: key,
		});
		const { data, total } = response;
		tableData.list = data || [];
		tableData.pagination = {
			total: Number(total) || 0,
			current: tableData.pagination.current,
			pageSize: tableData.pagination.pageSize,
			sizeChange: (size) => {
				tableData.pagination.current = size;
				getList(key);
			},
			onChange: (size) => {
				tableData.pagination.current = size;
				getList(key);
			},
		};
	} catch (error: any) {
		console.log(error);
	}
	tableData.loading = false;
};
onMounted(() => {
	getList(searchKey);
});

const dialogUpdateVisible = ref(false);
const dialogAddVisible = ref(false);

const saveData = reactive<ITableListItem>({
	departmentName: "",
	manager: "",
	location: "",
	employeesId: 1,
});
const updateData = reactive<ITableListItem>({
	departmentId: -1,
	departmentName: "",
	manager: "",
	location: "",
	employeesId: 1,
});

const saveSub = async (data?: ITableListItem) => {
	if (!data) {
		ElMessage.error("信息错误");
		return;
	}
	if(!data.employeesId){
		ElMessage.error("管理者不存在");
		return;
	}
	const response: IResponseData<ITableListItem> = await save(data);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("保存成功");
		dialogAddVisible.value = false;
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};

const showDetail = (data: ITableListItem) => {
	updateData.departmentId = data.departmentId;
	updateData.departmentName = data.departmentName;
	updateData.manager = data.manager;
	updateData.location = data.location;
	updateData.employeesId = data.employeesId;
	dialogUpdateVisible.value = true;
};
const updateSub = async (data?: ITableListItem) => {
	if (!data) {
		ElMessage.error("信息错误");
		return;
	}
	// Check if 'employeesId' exists in the data
	if (!data.employeesId) {
		ElMessage.error("管理者不存在");
		return;
	}
	const response: IResponseData<ITableListItem> = await update(data);
	const { code, message } = response;
	if (code === ResultCodeEnum.SUCCESS) {
		ElMessage.success("保存成功");
		dialogUpdateVisible.value = false;
		getList(searchKey);
	} else {
		ElMessage.error(message || "更新失败");
	}
};
const removeUser = async (id: number) => {
	// TODO
	const response: IResponseData<ITableListItem> = await removeData(id);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("删除成功");
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};

const searchAction = () => {
	getList(searchKey);
};
</script>
<template>
  <ScreenTable row-key="id" :data="tableData.list" :loading="tableData.loading" :pagination="tableData.pagination">

    <template #header>
      <div class="header-box">
        <div class="header-box__left">
          <el-input placeholder="请输入部门名称" v-model="searchKey.departmentName" style="width: 200px;" />
          <el-button type="primary" @click="searchAction">搜索</el-button>
        </div>
        <el-button type="primary" @click="dialogAddVisible = true">新增</el-button>
      </div>
    </template>

    <el-table-column fixed label="序号" type="index" :index="tableIndexMethod" width="80"> </el-table-column>
    <el-table-column label="部门名称" prop="departmentName" width="100"> </el-table-column>
    <el-table-column label="管理者" prop="manager" width="100"> </el-table-column>
    <el-table-column label="部门位置" prop="location"> </el-table-column>
    <el-table-column label="管理者ID" prop="employeesId" width="100"> </el-table-column>
    <el-table-column label="操作" prop="action" width="150" fixed="right">
      <template #default="scop">
        <el-button type="primary" link @click="showDetail(scop.row)">编辑</el-button>
        <el-button type="danger" link @click="removeUser(scop.row.departmentId)">删除</el-button>
      </template>
    </el-table-column>
  </ScreenTable>

  <!-- 修改 -->
  <el-dialog v-model="dialogUpdateVisible" top="20vh" title="修改信息">
    <el-form :model="updateData" label-width="auto" style="max-width: 600px">
      <el-form-item label="部门ID" style="display: none;">
        <el-input v-model="updateData.departmentId" />
      </el-form-item>
      <el-form-item label="部门名称">
        <el-input v-model="updateData.departmentName" />
      </el-form-item>
      <el-form-item label="部门管理者">
        <el-input v-model="updateData.manager" />
      </el-form-item>
      <el-form-item label="部门位置">
        <el-input v-model="updateData.location" />
      </el-form-item>
      <el-form-item label="管理者ID">
        <el-input v-model="updateData.employeesId" />
      </el-form-item>
      <el-button type="primary" @click="updateSub(updateData)">提交</el-button>
    </el-form>
  </el-dialog>

  <!-- 添加 -->
  <el-dialog v-model="dialogAddVisible" top="20vh" title="发布公告">
    <el-form :model="saveData" label-width="auto" style="max-width: 600px">
      <el-form-item label="部门ID" style="display: none">
        <el-input v-model="saveData.departmentId" />
      </el-form-item>
      <el-form-item label="部门名称">
        <el-input v-model="saveData.departmentName" />
      </el-form-item>
      <el-form-item label="部门管理者">
        <el-input v-model="saveData.manager" />
      </el-form-item>
      <el-form-item label="部门位置">
        <el-input v-model="saveData.location" />
      </el-form-item>
      <el-form-item label="管理者ID">
        <el-input v-model="saveData.employeesId" />
      </el-form-item>
      <el-button type="primary" @click="saveSub(saveData)">提交</el-button>
    </el-form>
  </el-dialog>
</template>
